package controller;

import gui.Frame;

import java.io.File;

import core.Model;
import core.net.XmlParser;
import core.utils.Variable;

/**
 * This class is meant to be the central class when it comes to converting user input and runtime events into changes in the model and frame as per 
 * the MVC framework. 
 */
public class Controller {
	private static final Model model = Model.getInstance();
	private Frame frame;
	private static Controller instance;
	private UpdateThread thread;
	//This should maybe be in Model instead?
	private int interval = 3;

	//Class is singleton, prevent instantiation.
	private Controller(){}

	/**
	 * Initializes controller with GUI frame. This method needs to be run before any actions can be fired.
	 * @param frame Frame for the controller to handle.
	 */
	public void initialize(Frame frame){
		instance.frame = frame;
		thread = new UpdateThread(frame);
	}

	/**
	 * Returns the singleton instance of the class.
	 * @return The singleton instance of the class.
	 */
	public static Controller getInstance(){
		if (instance == null){
			instance = new Controller();
		}
		return instance;
	}

	/**
	 * This method should be called when user has, through the GUI, called for an attempt to connect to web resources.
	 * When called, a thread is started which is responsible for continuously updating the model through the data
	 * collected from the server. This is done by, at a user-specified interval, fetching and parsing data using
	 * the classes in the <code>net</code> package.
	 * This leaves the main thread free to handle user input. 
	 */
	public void connectActionFired(){
		model.setConnectionStatus(true);
		frame.setConnected(true);
		thread.start(); 
	}

	/**
	 * This method handles the event in which a connection to web resources has failed for some reason. It is responsible for notifying the frame of
	 * the failure as well as making sure that no further attempts are made to collect data from the server.
	 */
	public void connectionFailed(){
		model.setConnectionStatus(false);
		frame.connectionFailed();
		thread.stop();
	}

	public void checkBoxClicked(Variable var, boolean checked){
		if (checked){
			System.out.println("checkbox added");
			model.addCheckedVariable(var);
		}
		else {
			System.out.println("checkbox removed");
			model.removeCheckedVariable(var);
		}
		frame.update();
	}
	
	public void readLog(File file){
		try {
			model.replaceData(XmlParser.parseLog(file));
			model.setConnectionStatus(true);
			frame.setConnected(true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		frame.update();
	}

	public void disconnect() {
		thread.stop();
		model.setConnectionStatus(false);
		frame.setConnected(false);
	}
}
